const websocket = require('ws') //引入websocket
const path = require('path')
const fileutils = require('../utils/file_utils')
const wss = new websocket.Server({ //配置server对象 端口号
    port : 9998
})
module.exports.listen = () => {
    wss.on('connection' , client => {
        console.log('有客户端连接了')
        client.on('message' ,async msg => {
            let payload = JSON.parse(msg)
            const action = payload.action 
            if(action === 'getData') {
                const chartName = payload.chartName
                let filepath = '../data/' + chartName + '.json'
                filepath = path.join(__dirname , filepath)
                const ret = await fileutils.getDatajson(filepath)
                payload.data = ret
                client.send(JSON.stringify(payload))//传回去的值
            } else {
                //所有连接的客户端    
                wss.clients.forEach(client => {
                    client.send(msg)
                })
            }
            console.log('客户端传数据过来了' + msg)
            
        })
    })
}